package com.jeasonzhao.commons.json;

import com.jeasonzhao.commons.parser.lex.LexTokenCollection;
import com.jeasonzhao.commons.utils.Algorithms;

public class JSONAssign extends JSONNode
{
    private static final long serialVersionUID = 1L;
    private String m_name = null;
    private JSONNode m_value = null;
    public JSONAssign(LexTokenCollection tks)
    {
        super(JSONNodeTypes.ASSIGN);
        this.m_tokens = tks;
    }

    public JSONAssign(String strName,Object value)
    {
        super(JSONNodeTypes.ASSIGN);
        setName(strName);
        setValue(value);
    }

    public JSONAssign(LexTokenCollection tks,String strName,JSONNode value)
    {
        super(JSONNodeTypes.ASSIGN);
        this.m_tokens = tks;
        this.m_name = strName;
        this.m_value = value;
    }

    public void setName(String strName)
    {
        this.m_name = strName == null ? null : Algorithms.removeBlanks(strName);
        if(null != this.m_name && this.m_name.length() < 1)
        {
            this.m_name = null;
        }
    }

    public void setValue(Object value)
    {
        if(value == null)
        {
            this.m_value = null;
        }
        else if(value instanceof JSONAssign)
        {
            this.m_value = ((JSONAssign) value).m_value;
        }
        else if(value instanceof JSONNode)
        {
            this.m_value = (JSONNode) value;
        }
        else
        {
            this.m_value = JSONNode.object2JSONNodeSafe(value);
        }
    }

    public String getName()
    {
        return m_name;
    }

    public JSONNode getValue()
    {
        return m_value;
    }

    public String toJSON(boolean isFullMode,int nLevel)
    {
        if(null == m_name || m_name.trim().length() < 1)
        {
            return null;
        }
        else
        {
            String valueString = m_value == null ? "" : m_value
                .setJavaScriptCompatible(this.javaScriptCompatible)
                .toJSON(isFullMode,nLevel + 1);
            if(valueString.length() < 1)
            {
                if(isFullMode == false)
                {
                    return "";
                }
            }
            return(isFullMode ? this.getPrefixSpace(nLevel) : "")
                + "\""+m_name+"\""
                + JSONParser.SPEC_ASSIGN_DELIMETER + valueString;
        }
    }
}
